package org.example.rocketmq.a01_quickstart;

import org.apache.commons.lang3.ThreadUtils;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.example.rocketmq.NamesrvAddr;

import java.time.Duration;
import java.util.List;

public class ConsumerPush {
    public static void main(String[] args) throws Exception {
        pushConsumer();
    }

    /**
     * 通过消息推送获取消息
     */
    public static void pushConsumer() throws Exception {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumer_push_group_01");
        consumer.setNamesrvAddr(NamesrvAddr.get());
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
        consumer.subscribe("TopicTest", "*");

        consumer.registerMessageListener(new MessageListenerConcurrently() { // 并发消费 / 顺序消费
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext context) {
                 System.out.printf("%s Receive New Message: %s %n", Thread.currentThread().getName(), list);
                System.out.println("消息数量：" + list.size());
                for (MessageExt messageExt : list) {
                    System.out.println(new String(messageExt.getBody()));
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        consumer.start();
        System.out.printf("Consumer started %n");


        ThreadUtils.sleep(Duration.ofSeconds(10));

        consumer.shutdown();
        System.out.printf("Consumer stop %n");
    }
}
